package com.ppch.wuwamanus.config;

import com.ppch.wuwamanus.exception.BusinessException;
import com.ppch.wuwamanus.exception.ErrorCode;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.exception.CosClientException;
import com.qcloud.cos.model.*;
import jakarta.annotation.Resource;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.File;

/**
 * Package:ppch-picture-backend
 * ClassName:CosManager
 *
 * @Author 泡泡茶壶
 * @Create 2024/12/23 11:30
 * @Version 1.0
 * Description:
 * 通用的cos对象存储业务方法类：包括基础的文件上传，下载方法
 */
@Component
@Data
@Slf4j
public class CosManager {

    @Resource
    private CosClientConfig cosClientConfig;

    @Resource
    private COSClient cosClient;

    /**
     * 本地文件上传
     * @param key 对象在存储桶中的唯一标识
     * @param file 要上传的文件
     * @return PutObjectResult
     */
    public PutObjectResult uploadObject(String key, File file){
        //初始化上传对象请求
        PutObjectRequest putObjectRequest = new PutObjectRequest(cosClientConfig.getBucket(), key, file);
        //调用COSClient中的putObject进行文件上传
        PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
        //返回上传结果对象
        return putObjectResult;
    }

    /**
     * 下载对象
     * @param key 对象在存储桶中的唯一标识
     */
    public COSObject downloadObject(String key) {
        GetObjectRequest getObjectRequest = new GetObjectRequest(cosClientConfig.getBucket(), key);
        return cosClient.getObject(getObjectRequest);
    }

    /**
     * 删除对象
     * @param key 对象在存储桶中的唯一标识
     */
    public void deleteObject(String key) {
        try {
            cosClient.deleteObject(cosClientConfig.getBucket(), key);
        } catch (CosClientException e) {
            log.error("删除COS对象存储文件错误："+e);
            throw new BusinessException(ErrorCode.OPERATION_ERROR,"删除COS对象存储文件错误："+e);
        }
    }

}
